﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Excel;
using System.Diagnostics;
using System.Windows.Forms.Integration;
using System.Windows.Forms;
using Microsoft.Office.Tools;

namespace QMagicBoxExcel
{
    public partial class ThisAddIn
    {
        // 文档与任务窗格的映射字典
        public Dictionary<Excel.Workbook, CustomTaskPane> _taskPanes = new Dictionary<Excel.Workbook, CustomTaskPane>();

       

        // 弹出窗口实例
        private PopOutWindow _popOutWindow;

        #region 初始化与事件订阅
        private void ThisAddIn_Startup(object sender, EventArgs e)
        {
            Debug.WriteLine("ThisAddIn: 插件启动");

            Application.WorkbookBeforeClose += Application_WorkbookBeforeClose;
            Application.WindowActivate += Application_WindowActivate;
        }
    
        #endregion

        #region 核心逻辑
        private void Application_WindowActivate(Excel.Workbook Doc, Excel.Window Wn)
        {
            try
            {
                var activeWorkbook = Application.ActiveWorkbook;
                if (activeWorkbook == null) return;

                Debug.WriteLine($"激活窗口: {activeWorkbook.Name}");

                // 隐藏其他文档的窗格（不自动创建新窗格）
                foreach (var pair in _taskPanes)
                {
                    if (pair.Key != activeWorkbook && pair.Value != null)
                    {
                        pair.Value.Visible = false;
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"窗口激活处理失败: {ex.Message}");
            }
        }
        //在Ribbon.cs中的BtnChatWithAI_Click事件中调用（重设任务窗格宽度确保WPS表格弹出宽度生效）
        public void ToggleTaskPaneForActiveWorkbook()
        {
            try
            {
                var activeWorkbook = Application.ActiveWorkbook;
                if (activeWorkbook == null)
                {
                    MessageBox.Show("当前没有活动文档", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // 按需创建任务窗格
                if (!_taskPanes.TryGetValue(activeWorkbook, out var pane))
                {
                    pane = CreateTaskPaneForWorkbook(activeWorkbook);
                    Debug.WriteLine($"延迟创建任务窗格: {activeWorkbook.Name}");
                }

                // 切换可见状态
                pane.Visible = !pane.Visible;

                // 设置任务窗格的宽度为 1080
                pane.Width = 1080;

                // 强制隐藏其他文档的窗格
                foreach (var pair in _taskPanes)
                {
                    if (pair.Key != activeWorkbook && pair.Value != null)
                    {
                        pair.Value.Visible = false;
                    }
                }

                Debug.WriteLine($"窗格状态切换: {activeWorkbook.Name} -> {pane.Visible}");
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"切换失败: {ex.Message}");
                MessageBox.Show($"操作失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region 重构的辅助方法
        private CustomTaskPane CreateTaskPaneForWorkbook(Excel.Workbook doc)
        {
            Debug.WriteLine($"创建任务窗格: {doc.Name}");

            var wpfControl = new AIChatUserControl();
            wpfControl.PopOutRequested += WpfControl_PopOutRequested;
            wpfControl.PopBackRequested += WpfControl_PopBackRequested;

            var host = new ElementHost
            {
                Dock = DockStyle.Fill,
                Child = wpfControl
            };
            wpfControl.OriginalHost = host;

            var wrapper = new UserControl { Dock = DockStyle.Fill };
            wrapper.Controls.Add(host);

            var ctp = CustomTaskPanes.Add(wrapper, "AI小助手", doc.Windows[1]);
            ctp.Visible = false;
            ctp.Width = 1080;
            ctp.VisibleChanged += (s, e) =>
                Debug.WriteLine($"可见性变更: {doc.Name} -> {ctp.Visible}");

            _taskPanes.Add(doc, ctp);
            return ctp;
        }
      
        #endregion

        #region 事件处理
        private void Application_WorkbookBeforeClose(Excel.Workbook Doc, ref bool Cancel)
        {
            try
            {
                Debug.WriteLine($"文档即将关闭: {Doc.Name}");

                if (_taskPanes.TryGetValue(Doc, out CustomTaskPane pane))
                {
                    pane.Dispose();
                    _taskPanes.Remove(Doc);
                    Debug.WriteLine($"已清理文档任务窗格: {Doc.Name}");
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"文档关闭清理错误: {ex.Message}");
            }
        }

        private void CustomTaskPane_VisibleChanged(object sender, EventArgs e)
        {
            var pane = sender as CustomTaskPane;
            Debug.WriteLine($"任务窗格可见性变更: {pane?.Title} -> {pane?.Visible}");
        }

        private void WpfControl_PopOutRequested(object sender, EventArgs e)
        {
            try
            {
                AIChatUserControl wpfControl = sender as AIChatUserControl;
                ElementHost host = FindHostForControl(wpfControl);

                // 先将 AIChatUserControl  从 ElementHost 中移除
                host.Child = null;

                // 创建一个新的WPF窗口并嵌入 AIChatUserControl 
                _popOutWindow = new PopOutWindow
                {
                    Content = wpfControl
                };
                _popOutWindow.Closed += PopOutWindow_Closed;
                wpfControl.IsInPopOutWindow = true;
                _popOutWindow.Width = 550;
                _popOutWindow.Show();

                // 隐藏整个任务窗格
                CustomTaskPane taskPane = FindTaskPaneForControl(wpfControl);
                ThisAddIn thisAddIn = Globals.ThisAddIn;
                thisAddIn.ToggleTaskPaneForActiveWorkbook();
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"弹出窗口时出错: {ex.Message}", "错误", (System.Windows.MessageBoxButton)MessageBoxButtons.OK, (System.Windows.MessageBoxImage)MessageBoxIcon.Error);
            }
        }

        private void WpfControl_PopBackRequested(object sender, EventArgs e)
        {
            try
            {
                AIChatUserControl wpfControl = sender as AIChatUserControl;
                if (wpfControl == null)
                    return;

                // 直接获取保存的 OriginalHost 引用
                ElementHost host = wpfControl.OriginalHost;
                if (host == null)
                    throw new Exception("OriginalHost 未设置，无法返回任务窗格。");

                // 关闭弹出窗口（若存在）
                PopOutWindow popOutWnd = FindPopOutWindowForControl(wpfControl);
                if (popOutWnd != null)
                {
                    popOutWnd.Content = null;
                    popOutWnd.Close();
                }

                // 将用户控件重新嵌入到原始宿主中
                host.Child = wpfControl;
                wpfControl.IsInPopOutWindow = false;

                // 显示整个任务窗格
                CustomTaskPane taskPane = FindTaskPaneForControl(wpfControl);
                ThisAddIn thisAddIn = Globals.ThisAddIn;
                thisAddIn.ToggleTaskPaneForActiveWorkbook();
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show($"返回任务窗格时出错: {ex.Message}", "错误",
                     (System.Windows.MessageBoxButton)MessageBoxButtons.OK, (System.Windows.MessageBoxImage)MessageBoxIcon.Error);
            }
        }
        private CustomTaskPane FindTaskPaneForControl(AIChatUserControl wpfControl)
        {
            foreach (var pair in _taskPanes)
            {
                UserControl wrapperControl = pair.Value.Control as UserControl;
                if (wrapperControl != null)
                {
                    foreach (Control control in wrapperControl.Controls)
                    {
                        if (control is ElementHost host && host.Child == wpfControl)
                        {
                            return pair.Value;
                        }
                    }
                }
            }
            return null;
        }

        private void PopOutWindow_Closed(object sender, EventArgs e)
        {
            PopOutWindow popOutWnd = sender as PopOutWindow;
            if (popOutWnd == null)
                return;

            AIChatUserControl wpfControl = popOutWnd.Content as AIChatUserControl;
            if (wpfControl == null)
                return;

            ElementHost host = wpfControl.OriginalHost;
            if (host == null)
                return;

            // 移除用户控件从弹出窗口
            popOutWnd.Content = null;

            // 将用户控件重新嵌入到原始宿主
            host.Child = wpfControl;
            wpfControl.IsInPopOutWindow = false;

            // 显示对应的任务窗格
            ShowTaskPaneForControl(wpfControl);
        }
        private void ShowTaskPaneForControl(AIChatUserControl wpfControl)
        {
            foreach (var pair in _taskPanes)
            {
                UserControl wrapperControl = pair.Value.Control as UserControl;
                if (wrapperControl != null)
                {
                    foreach (Control control in wrapperControl.Controls)
                    {
                        if (control is ElementHost host && host.Child == wpfControl)
                        {
                            pair.Value.Visible = true;
                            return;
                        }
                    }
                }
            }
        }
        private PopOutWindow FindPopOutWindowForControl(AIChatUserControl wpfControl)
        {
            if (_popOutWindow != null && _popOutWindow.Content == wpfControl)
            {
                return _popOutWindow;
            }
            return null;
        }
        private ElementHost FindHostForControl(AIChatUserControl wpfControl)
        {
            // 遍历 _taskPanes
            foreach (var pair in _taskPanes)
            {
                UserControl wrapperControl = pair.Value.Control as UserControl;
                if (wrapperControl != null)
                {
                    foreach (Control control in wrapperControl.Controls)
                    {
                        if (control is ElementHost host && host.Child == wpfControl)
                        {
                            return host;
                        }
                    }
                }
            }
            return null;
        }

        #endregion

        #region 资源清理
        private void ThisAddIn_Shutdown(object sender, EventArgs e)
        {
            Debug.WriteLine("插件关闭，清理资源...");

            foreach (var pane in _taskPanes.Values)
            {
                pane.Dispose();
            }
            _taskPanes.Clear();

            _popOutWindow?.Close();
            _popOutWindow = null;
        }
        #endregion

        #region VSTO生成代码
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
        }
        #endregion
    }
    //弹窗
    public class PopOutWindow : System.Windows.Window
    {
        public PopOutWindow()
        {
            this.Title = "AI小助手";
            this.Width = 400;
            this.Height = 600;
            this.Background = System.Windows.Media.Brushes.White;
            this.BorderBrush = System.Windows.Media.Brushes.LightGray;
            this.BorderThickness = new System.Windows.Thickness(1);
            this.Topmost = true;
            this.Icon = new System.Windows.Media.Imaging.BitmapImage(new Uri("pack://application:,,,/QMagicBoxExcel;component/Icon/人工智能.ico"));
        }
    }
}